﻿using AuApmt.Models.Common;
using AuApmt.Models.DbModels;
using AuApmt.Services.App.HttpAuthInfo;
using Microsoft.AspNetCore.Mvc.Filters;

namespace AuApmt.Services.App.ActionFilters
{
    [AttributeUsage(AttributeTargets.Method)]
    public class UserTypeRestrictedAttribute(
        UserType level = UserType.Staff)
        : Attribute, IFilterFactory
    {
        public bool IsReusable => false;
        public UserType Level { get; set; } = level;

        public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
        {
            var f = serviceProvider.GetRequiredService<UserTypeRestrictedFilter>();
            f.Level = Level;
            return f;
        }

        public class UserTypeRestrictedFilter(
            HttpUserInfoService httpUserInfoService
            ) : IAsyncResourceFilter
        {
            public UserType Level { get; set; }

            public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
            {
                var type = httpUserInfoService.UserInfo.Value.Type;
                if(type < Level)
                {
                    var resp = new ApiResponse(null, false, "无权限");
                    context.Result = resp.BuildResult();
                }
                else
                    await next();
            }
        }
    }
    public static class UserTypeRestrictedAttributeExtensions
    {
        public static IServiceCollection AddUserTypeRestrictedFilter(this IServiceCollection services)
        {
            services.AddScoped<UserTypeRestrictedAttribute.UserTypeRestrictedFilter>();
            return services;
        }
    }
}
